
import PyPDF2
import csv
import chardet

def get_file_encoding(file_path):
    with open(file_path, 'rb') as f:
        result = chardet.detect(f.read())
        return result['encoding']

def parse_catalog(csv_file_path):
    bookmarks = []
    file_encoding = get_file_encoding(csv_file_path)
    with open(csv_file_path, 'r', encoding=file_encoding) as csv_file:
        reader = csv.reader(csv_file)
        for row in reader:
            if len(row) == 2:
                bookmark_name, page_num = row
                try:
                    page_num = int(page_num)
                    bookmarks.append((bookmark_name, page_num))
                except ValueError:
                    continue
            # print(f"正在处理第{page_num}行内容: {bookmark_name}")        
    return bookmarks

def add_bookmarks(pdf_path, bookmarks):
    with open(pdf_path, 'rb') as file:
        pdf = PyPDF2.PdfReader(file)
        writer = PyPDF2.PdfWriter()
        for page_num, page in enumerate(pdf.pages):
            writer.add_page(page)
            for bookmark_name, bm_page_num in bookmarks:
                if bm_page_num == page_num + 1:
                    writer.add_outline_item(bookmark_name, page_num)
                    print(f"正在处理第{page_num}行内容: {bookmark_name}")
        with open('new_pdf_with_bookmarks.pdf', 'wb') as new_file:
            writer.write(new_file)

           
# 假设CSV，PDF文件的路径
csv_file_path = r"E:\\bookmarks.csv"
pdf_path = r"E:\\fa1322.pdf"

bookmarks_1 = parse_catalog(csv_file_path)
add_bookmarks(pdf_path, bookmarks_1)